<template>
  <div class="page">
    <!--  页面头部  -->
    <div class="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>学生管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!--  搜索区,表单  -->
    <div>
      <el-form :inline="true" :model="searchBody" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input v-model="searchBody.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchBody.sex" placeholder="请选择性别" @change="getStudentListBySex">
            <el-option v-for="item in sexDict" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="searchBody.phone" placeholder="请填写电话"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 操作区   -->
    <div>
      <el-button type="success" @click="dialogFormVisible = true">新增</el-button>
    </div>
    <!--  表格+分页  -->
    <div>
      <el-table
          :data="tableData"
          style="width: 100%">
        <el-table-column
            prop="id"
            label="id"
            width="180">
        </el-table-column>
        <el-table-column
            prop="name"
            label="姓名"
            width="180">
        </el-table-column>
        <el-table-column
            prop="sex"
            label="性别">
          <template slot-scope="scope">
            <el-tag
                type="info"
                effect="dark">
              {{ getLabel(scope.row.sex) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="age"
            label="年龄">
        </el-table-column>
        <el-table-column
            prop="phone"
            label="电话">
        </el-table-column>


        <el-table-column
            label="操作">
          <template v-slot:default = "scope">
            <el-button type="danger" @click="delStudent(scope.row.id)">删除</el-button>
            <el-button type="primary" @click="updateWindow(scope.row)">更新</el-button>
          </template>
        </el-table-column>


      </el-table>
      <div class="pagination">
        <el-pagination
            background
            layout="prev, pager, next"
            :current-page="searchBody.pageNum"
            :page-size="searchBody.pageSize"
            @current-change="pageNumChange"
            :total="total">
        </el-pagination>
      </div>
    </div>
    <!-- 添加学生信息-->
    <el-dialog :close-on-click-modal="false" title="新增学生" :visible.sync="dialogFormVisible">
      <el-form :model="studentAddBody" ref="studentAddRef">
        <el-form-item
            prop="name"
            label="姓名"
            :rules="[
                { required: true, message: '请输入姓名', trigger: 'blur' },
             ]"
        >
          <el-input v-model="studentAddBody.name"></el-input>
        </el-form-item>

        <el-form-item
            prop="sex"
            label="性别"
            :rules="sexRule"
        >
          <el-select v-model="studentAddBody.sex" placeholder="请选择性别">
            <el-option v-for="item in sexDict" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="年龄" prop="age" :rules="ageValidator">
          <el-input v-model.number="studentAddBody.age"></el-input>
        </el-form-item>

        <el-form-item
            prop="phone"
            label="手机号"
            :rules="phoneValidator"
        >
          <el-input v-model="studentAddBody.phone"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addStudent">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 更新信息-->
    <el-dialog :close-on-click-modal="false" title="输入更新信息" :visible.sync="updateDialogFormVisible">
      <el-form :model="updateObj" ref="studentUpdateRef">
        <el-form-item
            prop="name"
            label="姓名"
            :rules="[
                { required: true, message: '请输入姓名', trigger: 'blur' },
             ]"
        >
          <el-input v-model="updateObj.name"></el-input>
        </el-form-item>

        <el-form-item
            prop="sex"
            label="性别"
            :rules="sexRule"
        >
          <el-select v-model="updateObj.sex" placeholder="请选择性别">
            <el-option v-for="item in sexDict" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="年龄" prop="age" :rules="ageValidator">
          <el-input v-model.number="updateObj.age"></el-input>
        </el-form-item>

        <el-form-item
            prop="phone"
            label="手机号"
            :rules="phoneValidator"
        >
          <el-input v-model="updateObj.phone"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateStudent">确定更新</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {deleteStudent, getDictionaries, insertStudent, pageList, updateStudent} from "@/api/student-api";

export default {
  name: "StudentManager",
  data() {
    const validatePhone = (rule, value, callback) => {
      let phoneReg = /^1[^012]\d{9}$/
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else if (!phoneReg.test(value)) {
        callback(new Error('手机号格式不正确'));
      } else {
        callback();
      }
    };
    const validateAge = (rule, value, callback) => {
      if (value && isNaN(value)) {
        callback(new Error('年龄请输入数字类型'));
      } else {
        callback();
      }
    };


    return {
      searchBody: {
        pageNum: 1,
        pageSize: 2,
        name: '',
        sex: 0,
        phone:""
      },
      total:0,
      tableData: [],
      dialogFormVisible:
          false,
      studentAddBody:
          {
            name: "",
            sex: "",
            age: "",
            phone: "",
          }
      ,
      phoneValidator: [
        {required: true, message: '请输入手机号', trigger: 'blur'},
        {validator: validatePhone, trigger: ['blur', 'change']}
      ],
      ageValidator:[
        { required: true, message: '请输入年龄', trigger: 'blur' },
        { validator: validateAge, trigger: 'blur' }
      ],
      sexRule: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      sexDict:[],
      updateDialogFormVisible:false,
      updateObj:{},

    }
  },

  mounted() {
    this.getStudentList();
    getDictionaries().then(res=>{
      this.sexDict = res.data.data
    })
  },
  created() {
    // 从路由查询参数中获取性别
    const querySex = this.$route.query.sex || 0;

    // 设置搜索条件中的性别
    this.searchBody.sex = querySex;

    // 根据性别获取学生列表
    this.getStudentListBySex(querySex);
  },

  methods: {
    //更新学生信息
    updateWindow(student) {
      this.updateObj = student;
      this.updateDialogFormVisible = true;
    },
    //删除功能
    delStudent(id) {
      this.$confirm('确认删除学生信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteStudent(id).then(res => {
          if (res.data.code === 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            // 重新加载列表
            this.searchBody.pageNum = 1
            this.getStudentList()
          }else {
            this.$alert( res.data.msg, '删除失败', {
              confirmButtonText: '确定',
            });
          }
        })
      }).catch(()=>{

      })
    },
    //刷新列表
    getLabel(sexValue) {
      return this.sexDict.find(item => item.value === sexValue)?.label;
    },
    //查询功能
    search() {
      this.getStudentList()
    },

    //点击性别按钮直接出现数据
    getStudentListBySex(sex) {
      this.searchBody.sex = sex;
      // 调用 getStudentList() 方法刷新页面数据
      this.getStudentList();
    },
    //翻页
    pageNumChange(pageNum) {
      this.searchBody.pageNum = pageNum;
      this.getStudentList();
    },
    //增加学生信息
    addStudent() {
      // 获取用户输入
      this.$refs.studentAddRef.validate((valid) => {
        if (valid) {
          console.log('表单校验通过');
          // 代表表单校验通过了，可以发送请求了
          insertStudent(this.studentAddBody).then(res => {
            if (res.data.code === 200) {
              this.$message({
                message: '新增成功',
                type: 'success'
              });
              this.dialogFormVisible = false;
              this.getStudentList();
            } else {
              this.$alert(res.data.msg, '操作失败', {
                confirmButtonText: '确定',
              });
            }
          }).catch(err => {
            console.log(err);
          });
        } else {
          console.log('表单校验失败');
          return false;
        }
      });
    },
    //更新功能
    updateStudent() {
      // 获取用户输入
      this.$refs.studentUpdateRef.validate().then(() => {
        updateStudent(this.updateObj).then(res => {
          if (res.data.code === 200) {
            this.$message({
              message: '新增成功',
              type: 'success'
            });
            this.updateDialogFormVisible = false
            this.getStudentList();
          }else {
            this.$alert( res.data.msg, '更新失败', {
              confirmButtonText: '确定',
            });
          }
        })
      }).catch(err => {
        console.log(err)
      })
    },
    getStudentList() {
      pageList(this.searchBody).then((res) => {
        if (res.data.code === 200) {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        }else {
          this.$alert( res.data.msg, '获取失败', {
            confirmButtonText: '确定',
          });
        }
      }).catch(err => {
        console.log(err)
      });
    },
  },

}
</script>

<style scoped>
.page {
  padding: 20px;
}

.header {
  padding: 10px;
}

.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
